package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.AccessTokenDto;
import com.zzyl.dto.Code2sessionResultDto;
import com.zzyl.dto.PhoneNumberDto;
import com.zzyl.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxServiceImpl  implements WxService {
    @Override
    public Code2sessionResultDto getCode2Session(String jsCode) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", "wxe0560bccee7d540c");
        map.put("secret", "e966bd1f7f328c122d56aee50618d95f");
        map.put("js_code", jsCode);
        map.put(" grant _type", "authorization_code");
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String res = HttpUtil.get(url, map);
        Code2sessionResultDto code2sessionResultDto = JSONUtil.toBean(res, Code2sessionResultDto.class);
        return code2sessionResultDto;
    }

    @Override
    public AccessTokenDto getAccessToken() {

        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> map = new HashMap<>();
        map.put("appid","wxe0560bccee7d540c");
        map.put("secret","e966bd1f7f328c122d56aee50618d95f");
        map.put("grant_type","client_credential");
        String res = HttpUtil.get(url, map);
        AccessTokenDto accessTokenDto = JSONUtil.toBean(res, AccessTokenDto.class);
        return accessTokenDto;

    }
    @Override
    public PhoneNumberDto getPhoneNumber(String token, String phoneCode) {
        //POST https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN
        String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+token;
        HashMap<String, Object> param = new HashMap<>();
        param.put("code",phoneCode);
        String json = JSONUtil.toJsonStr(param);
        String res = HttpUtil.post(url, json);
        PhoneNumberDto phoneNumberDto = JSONUtil.toBean(res, PhoneNumberDto.class);

        return phoneNumberDto;
    }

}
